<template>
  <div class="forum-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>话题详情</span>
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </div>
      </template>

      <!-- 话题内容 -->
      <div v-if="topicDetail" class="topic-content">
        <div class="topic-header">
          <h1 class="topic-title">{{ topicDetail.title }}</h1>
          <div class="topic-meta">
            <el-tag v-if="topicDetail.isFirst=='1'" type="warning" size="small">置顶</el-tag>
            <el-tag v-if="topicDetail.viewCount>=20" type="danger" size="small">热门</el-tag>
            <el-tag :type="getCategoryType(topicDetail.category)">{{ getCategoryText(topicDetail.category) }}</el-tag>
            <span class="author-info">作者：{{ topicDetail.createUser }}</span>
            <span class="time-info">发布时间：{{ topicDetail.createTime }}</span>
            <span class="view-info">浏览：{{ topicDetail.viewCount }}</span>
          </div>
        </div>

        <div class="topic-body">
          <div class="content-text">{{ topicDetail.content }}</div>
        </div>

        <!-- 回复列表 -->
        <div class="reply-section">
          <h3 class="reply-title">回复列表 ({{ replies.length }})</h3>
          <div v-if="replies.length > 0" class="reply-list">
            <el-card v-for="reply in replies" :key="reply.id" class="reply-item">
              <div class="reply-header">
                <span class="reply-author">{{ reply.createUser }}</span>
                <span class="reply-time">{{ reply.createTime }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </el-card>
          </div>
          <div v-else class="no-replies">暂无回复，快来发表第一条回复吧！</div>
        </div>

        <!-- 回复表单 -->
        <div class="reply-form-section">
          <h3 class="reply-form-title">发表回复</h3>
          <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules" label-width="80px">
            <el-form-item label="回复内容" prop="content">
              <el-input v-model="replyForm.content" type="textarea" :rows="4" placeholder="请输入回复内容"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitReply" :loading="submittingReply">发表回复</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 加载中状态 -->
      <div v-else class="loading-state">
        <el-empty description="加载中..." />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { forumDetail, forumReply, forumReplyList } from '@/request/forum'

// 路由相关
const route = useRoute()
const router = useRouter()
const topicId = route.params.id

// 数据
const topicDetail = ref(null)
const replies = ref([])
const submittingReply = ref(false)

// 回复表单
const replyFormRef = ref(null)
const replyForm = ref({
  content: ''
})

// 回复表单验证规则
const replyRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 2000, message: '回复内容长度在 2 到 2000 个字符', trigger: 'blur' }
  ]
}

// 获取话题详情
const getTopicDetail = async () => {
  try {
    // 使用专门的话题详情接口获取数据
    const response = await forumDetail(topicId)
    
    if (response) {
      topicDetail.value = response

    } else {
      ElMessage({ message: '话题不存在', type: 'error' })
      router.push('/front/forum')
    }
  } catch (error) {
    ElMessage({ message: '获取话题详情失败', type: 'error' })
    console.error('获取话题详情失败:', error) 
  }
}

getTopicDetail()

const getReplyList = async () => {
  try {
    const response = await forumReplyList(topicId)
    if (response) {
      replies.value = response
    } else {
      ElMessage({ message: '获取回复列表失败', type: 'error' })
    }
  } catch (error) {
    ElMessage({ message: '获取回复列表失败', type: 'error' })
    console.error('获取回复列表失败:', error) 
  }
}
// 获取回复列表
getReplyList()

// 提交回复
const submitReply = () => {
  replyFormRef.value.validate((valid) => {
    if (valid) {
      submittingReply.value = true
      
      // 准备回复数据
      const replyData = {
        forumId: topicId,
        content: replyForm.value.content
      }
      
      // 使用专门的发表回复接口
      forumReply(replyData).then(() => {
        // 回复成功后刷新话题详情，以获取最新的回复列表
        getReplyList()
        replyForm.value.content = ''
        ElMessage({ message: '回复发表成功', type: 'success' })
      }).catch(error => {
        ElMessage({ message: '回复发表失败', type: 'error' })
        console.error('发表回复失败:', error)
      }).finally(() => {
        submittingReply.value = false
      })
    }
  })
}

// 返回列表
const goBack = () => {
  router.push('/front/forum')
}

// 根据分类获取标签类型
const getCategoryType = (category) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  }
  return typeMap[category] || 'info'
}

// 获取分类文本
const getCategoryText = (category) => {
  const textMap = {
    1: '旅行攻略',
    2: '线路推荐',
    3: '摄影分享',
    4: '装备讨论',
    5: '结伴同行'
  }
  return textMap[category] || '其他'
}

</script>

<style scoped>
.forum-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topic-content {
  margin-top: 20px;
}

.topic-header {
  margin-bottom: 20px;
}

.topic-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.topic-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  color: #666;
  font-size: 14px;
}

.topic-body {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 30px;
}

.content-text {
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
}

.reply-section {
  margin-bottom: 30px;
}

.reply-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.reply-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.reply-item {
  border-left: 4px solid #1890ff;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.reply-author {
  font-weight: bold;
  color: #333;
}

.reply-time {
  color: #999;
  font-size: 12px;
}

.reply-content {
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

.no-replies {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.reply-form-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.reply-form-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.loading-state {
  text-align: center;
  padding: 60px 0;
}
</style>